﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.ESS.APP.App_UI.Forms;
using KPIS.GERP.ESS.APP.App_UI.Commons;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.MODEL;
//using KPIS.GERP.ESS.IBLL;
//using KPIS.GERP.ESS.BLL;
//using KPIS.GERP.ESS.MODEL;
using _WebShared.Classes;
using Telerik.Web.UI;

namespace KPIS.GERP.ESS.APP.App_UI.UserControls
{
    public partial class Mail_Petition : System.Web.UI.UserControl
    {
        Main main = new Main();
        ESS.BLL.B_MessageSend send = new ESS.BLL.B_MessageSend();
        ESS.BLL.B_MessageReply reply = new ESS.BLL.B_MessageReply();
        FIM_Employees.FIM_Employees emp = new FIM_Employees.FIM_Employees();
        FIM_Petitions.FIM_Petitions pet = new FIM_Petitions.FIM_Petitions();
        FIM_PetitionDtls.FIM_PetitionDtls petd = new FIM_PetitionDtls.FIM_PetitionDtls();
        B_HrmEmployees emplist = new B_HrmEmployees();
        B_SECURITY_Users user = new B_SECURITY_Users();
        BGM_MAS_ExpenseGroup.BGM_MAS_ExpenseGroup expgrp = new BGM_MAS_ExpenseGroup.BGM_MAS_ExpenseGroup();

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void LoadData(string strSendSeq, FIM_Petitions.M_FIM_Petitions info, bool bEdit
            , string strApprovePathSeq, string strStatus, string strSender)
        {
            lblSendSeq.Text = strSendSeq;
            lblApprovePathSeq.Text = strApprovePathSeq;
            lblPetitionSeq.Text = info.petition_seq.ToString();
            lblSendDate.Text = "เมื่อวันที่   " + info.petition_date.Value.ToShortDateString();
            lblRefNo.Text = info.ref_no;
            lblDirectPayName.Text = (info.direct_pay == "1" ? "จ่ายตรง" : "จ่ายผ่านส่วนราชการ");
            lblBgmExpGrpName.Text = expgrp.GetInfo(info.bgm_exp_grp_seq.ToString()).bgm_exp_grp_name;

            LoadMoneyRequests();
            //LoadDDLEmpSeq();
            bool bEnable = strStatus == "2";
            cmdApprove.Enabled = !bEnable && bEdit;
            cmdForword.Enabled = !bEnable && bEdit;
            cmdSendBack.Enabled = !bEnable && bEdit;
            PanelOption.Visible = true;
            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendBack.Visible = false;
            PanelSend.Visible = false;
            txtRemark.Text = "";
            SetApproverRight();
        }

        protected void LoadMoneyRequests()
        {
            GrdViewAll.DataSource = petd.GetFull(lblPetitionSeq.Text);
            GrdViewAll.DataBind();
        }

        protected void SetApproverRight()
        {
            cmdApprove.Visible = user.CheckIsApprover(Session["EmpSeq"].ToString());
        }

        public void cmdApprove_Click(object sender, EventArgs e)
        {
            PanelApprove.Visible = true;
            PanelSendTo.Visible = false;
            lblMode.Text = "A";

            PanelSendBack.Visible = true;
            // button
            PanelOption.Visible = false;
            PanelSend.Visible = true;
        }

        protected void cmdForword_Click(object sender, EventArgs e)
        {
            PanelApprove.Visible = false;
            PanelSendTo.Visible = true;
            lblMode.Text = "F";

            PanelSendBack.Visible = true;
            // button
            PanelOption.Visible = false;
            PanelSend.Visible = true;

            ddlApprover.SelectedIndex = -1;
            lblApproverClassName.Text = "";
            lblApproverEmpSeq.Text = "";
            lblApproverExecPosName.Text = "";
            lblApproverJobsiteName.Text = "";
            lblApproverPosName.Text = "";
            lblError.Text = "";
        }

        protected void cmdSendBack_Click(object sender, EventArgs e)
        {
            lblMode.Text = "B";

            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendBack.Visible = true;
            // button
            PanelOption.Visible = false;
            PanelSend.Visible = true;
            lblError.Text = "";
        }

        protected void LoadEmpInfo(string strEmpSeq)
        {
            if (strEmpSeq.Length > 0)
            {
                DataTable dtb = emplist.GetInfo(Convert.ToInt32(strEmpSeq));

                lblApproverEmpSeq.Text = dtb.Rows[0]["sequence"].ToString();
                ddlApprover.Text = dtb.Rows[0]["full_name"].ToString();
                lblApproverPosName.Text = dtb.Rows[0]["pos_name"].ToString();
                lblApproverClassName.Text = dtb.Rows[0]["class_name"].ToString();
                lblApproverExecPosName.Text = dtb.Rows[0]["exec_pos_name"].ToString();
                lblApproverJobsiteName.Text = dtb.Rows[0]["job_site_name"].ToString();
            }
        }


        private bool directApprove = false;
        public string Approve(string remark)
        {
            cmdApprove_Click(new Object(), new EventArgs());
            txtRemark.Text = remark;
            return cmdSendClick();
        }

        public void cmdSend_Click(object sender, EventArgs e)
        {
            cmdSendClick();
        }

        public string cmdSendClick()
        {
            try
            {
                int nEmpSeqLogin = SsMng.EmpSeqI;
                //BGM_ProjectOperation.M_BGM_ProjectOperation operInfo = new BGM_ProjectOperation.M_BGM_ProjectOperation();
                FIM_Petitions.M_FIM_Petitions petInfo = new FIM_Petitions.M_FIM_Petitions();
                ESS.MODEL.M_MessageSend info = new ESS.MODEL.M_MessageSend();
                ESS.MODEL.M_MessageReply replyInfo = new ESS.MODEL.M_MessageReply();
                string strPetitionSeq = lblPetitionSeq.Text;
                // By Aek 2014-07-29
                // remark: in forwarding FromEmpSeq should be the previous emp_seq in message_send
                // string strFromEmpSeq = Session["EmpSeq"].ToString();
                var messageSendPrev = send.GetFull(null, null, null, null, null, null, null, lblSendSeq.Text)[0];
                string strFromEmpSeq = messageSendPrev.to_emp_seq.ToString();
                string strFromPosSeq = messageSendPrev.to_pos_seq.ToString();
                
                int nFromEmpSeq = Convert.ToInt32(strFromEmpSeq);
                int nFromPosSeq = Convert.ToInt32(strFromPosSeq);

                Nullable<int> nToEmpSeq = null;
                Nullable<int> nToPosSeq = null;
                Nullable<int> nWodEmpSeq = nEmpSeqLogin == nFromEmpSeq ? (int?)null : nEmpSeqLogin;

                bool bLeaf = true;
                string strSendSeq = lblSendSeq.Text;
                string strToEmpSeq = lblApproverEmpSeq.Text;

                if (strToEmpSeq.Length == 0 && ddlApprover.Visible)
                {
                    lblError.Text = "คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง";
                    return lblError.Text;
                }
                else
                {
                    lblError.Text = "";
                }

                while (bLeaf)
                {
                    ESS.MODEL.M_MessageSend sendInfo = send.GetInfo(strSendSeq);
                    string strFromSendSeq = sendInfo.from_send_seq.ToString();

                    if (string.IsNullOrEmpty(strFromSendSeq))
                    {
                        bLeaf = false;
                        nToEmpSeq = sendInfo.from_emp_seq;
                        nToPosSeq = send.GetPosSeqFromEmpSeq(Convert.ToString(nToEmpSeq));
                    }

                    strSendSeq = strFromSendSeq;
                }

                switch (lblMode.Text)
                {
                    case "A":
                        petInfo.petition_seq = Convert.ToInt32(strPetitionSeq);
                        petInfo.record_status = "A";
                        petInfo.updated_by = nEmpSeqLogin;
                        petInfo.updated_when = DateTime.Now;
                        pet.ChangeStatus(petInfo);

                        //IList<FIM_MoneyRequestDtls.M_FIM_MoneyRequestDtls> mrdInfo = .GetFull(strMoneyReqSeq);
                        //for (int i = 0; i < mrdInfo.Count; i++)
                        //{
                        //    FIM_MoneyRequestDtls.M_FIM_MoneyRequestDtls expInfo = mrdInfo[i];
                        //    BGM_ProjectOperationReport.M_BGM_ProjectOperationReport reportInfo = new BGM_ProjectOperationReport.M_BGM_ProjectOperationReport();
                        //    reportInfo.money_req_dtls_seq = expInfo.money_req_dtls_seq;
                        //    reportInfo.used_amount = expInfo.bath_amount;
                        //    reportInfo.cal_amount = - expInfo.bath_amount;
                        //    reportInfo.rpt_type = 5;//กันเงิน
                        //    reportInfo.created_by = nEmpSeq;
                        //    reportInfo.created_when = DateTime.Now;
                        //    opRpt.Insert(reportInfo);
                        //}

                        replyInfo.reply_date = DateTime.Today;
                        replyInfo.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                        replyInfo.reply_type = "1";
                        replyInfo.reply_text = "อนุมัติ";
                        replyInfo.from_emp_seq = nFromEmpSeq;
                        replyInfo.from_pos_seq = nFromPosSeq;
                        replyInfo.to_emp_seq = nToEmpSeq;
                        replyInfo.to_pos_seq = nToPosSeq;
                        replyInfo.wod_emp_seq = nWodEmpSeq;
                        replyInfo.from_send_seq = Convert.ToInt32(lblSendSeq.Text);
                        replyInfo.message_status = "0";
                        replyInfo.remarks = txtRemark.Text;
                        replyInfo.created_by = nEmpSeqLogin;
                        replyInfo.created_when = DateTime.Now;
                        reply.Insert(replyInfo);

                        info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                        info.message_status = "2";
                        info.wod_emp_seq = nWodEmpSeq;
                        info.updated_by = nEmpSeqLogin;
                        info.updated_when = DateTime.Now;
                        send.UpdateMessageStatus(info);
                        break;
                    case "F":
                        petInfo.petition_seq = Convert.ToInt32(strPetitionSeq);
                        petInfo.record_status = "P";
                        petInfo.updated_by = nEmpSeqLogin;
                        petInfo.updated_when = DateTime.Now;
                        pet.ChangeStatus(petInfo);

                        info.send_date = DateTime.Today;
                        info.ref_seq = main.ConvertNullInt(strPetitionSeq);
                        info.ref_type = "fim_money_requests";
                        info.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                        info.send_text = "ส่งขออนุมัติเบิกเงินในระบบ GFMIS " + lblRefNo.Text;
                        info.from_emp_seq = nFromEmpSeq;
                        info.from_pos_seq = nFromPosSeq;
                        info.to_emp_seq = main.ConvertNullInt(strToEmpSeq);
                        info.to_pos_seq = send.GetPosSeqFromEmpSeq(strToEmpSeq);
                        info.from_send_seq = main.ConvertNullInt(lblSendSeq.Text);
                        info.remarks = txtRemark.Text;
                        info.message_status = "0";
                        info.approve_path_seq = main.ConvertNullInt(lblNewApprovePathSeq.Text);
                        info.created_by = nEmpSeqLogin;
                        info.created_when = DateTime.Now;
                        send.Insert(info);

                        info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                        info.message_status = "2";
                        info.wod_emp_seq = nWodEmpSeq;
                        info.updated_by = nEmpSeqLogin;
                        info.updated_when = DateTime.Now;
                        send.UpdateMessageStatus(info);
                        break;
                    case "B":
                        petInfo.petition_seq = Convert.ToInt32(strPetitionSeq);
                        petInfo.record_status = "R";
                        petInfo.updated_by = nEmpSeqLogin;
                        petInfo.updated_when = DateTime.Now;
                        pet.ChangeStatus(petInfo);

                        replyInfo.reply_date = DateTime.Today;
                        replyInfo.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                        replyInfo.reply_type = "0";
                        replyInfo.reply_text = "ส่งกลับมาเพื่อแก้ไข";
                        replyInfo.from_emp_seq = nFromEmpSeq;
                        replyInfo.from_pos_seq = nFromPosSeq;
                        replyInfo.to_emp_seq = nToEmpSeq;
                        replyInfo.to_pos_seq = nToPosSeq;
                        replyInfo.wod_emp_seq = nWodEmpSeq;
                        replyInfo.from_send_seq = Convert.ToInt32(lblSendSeq.Text);
                        replyInfo.remarks = txtRemark.Text;
                        replyInfo.message_status = "0";
                        replyInfo.created_by = nEmpSeqLogin;
                        replyInfo.created_when = DateTime.Now;
                        reply.Insert(replyInfo);

                        info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                        info.message_status = "2";
                        info.wod_emp_seq = nWodEmpSeq;
                        info.updated_by = nEmpSeqLogin;
                        info.updated_when = DateTime.Now;
                        send.UpdateMessageStatus(info);
                        break;
                }

                ((TaskListsPopUp) Page).cmdViewRequest_Click(null, null);
            }
            catch (Exception ex)
            {
                string errorStr = ex.Message + " " + ex.InnerException;
                if (!directApprove) main.MessageAlert(Page, errorStr);
                return errorStr;
            }
            return "";
        }

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendBack.Visible = false;
            // button
            PanelOption.Visible = true;
            PanelSend.Visible = false;
        }

        protected void ddlApprover_DataBound(object sender, EventArgs e)
        {
            //set the initial footer label
            ((Literal)ddlApprover.Footer.FindControl("RadComboItemsCount")).Text = Convert.ToString(ddlApprover.Items.Count);
        }

        protected void ddlApprover_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            ddlApprover.DataSource = emplist.ListEmployeeByType("('1', '2', '3')", "");
            ddlApprover.DataBind();
        }

        protected void ddlApprover_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((DataRowView)e.Item.DataItem)["full_name"].ToString();
            e.Item.Value = ((DataRowView)e.Item.DataItem)["sequence"].ToString();
        }

        protected void ddlApprover_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadEmpInfo(ddlApprover.SelectedValue);
        }
    }
}